package com.tacademy.lbs.server;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.Reader;
import java.util.Date;
import java.util.List;
import javax.jdo.PersistenceManager;
import javax.jdo.annotations.Persistent;
import javax.servlet.http.*;

import com.tacademy.lbs.server.model.Place;
import com.tacademy.lbs.server.model.PlaceParser;

@SuppressWarnings("serial")
public class AddLocationServlet extends HttpServlet {
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		request.setCharacterEncoding("utf-8");
		
		String id = request.getParameter("id");
		String location = request.getParameter("location");
		String user = request.getParameter("user");
		Place place = new Place();
		place.setId(id);
		place.setLocation(location);
		place.setUser(user);
		savePlace(place);
		
		PrintWriter writer = response.getWriter();
		writer.print("OK");
	}
	
	private void savePlace(Place place) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			// ... do stuff with pm ...
			place.setCount(1);
			place.setDate(new Date());
			StringBuilder query = new StringBuilder("select from ");
			query.append(Place.class.getName());
			query.append("  where id == '").append(place.getId()).append("'");
			
			@SuppressWarnings("unchecked")
			List<Place> places = (List<Place>)pm.newQuery(query.toString()).execute();
			if (places.size() > 0) {
				Place storedPlace = places.get(0);
				place.setCount(storedPlace.getCount() + 1);
				place.setKey(storedPlace.getKey());
			}
			pm.makePersistent(place);
		} finally {
			pm.close();
		}
	}
}
